package com.instpower.things.handlers;

import com.instpower.things.helper.Checksum;
import com.instpower.things.instpower.*;
import com.instpower.things.service.InstService;
import com.instpower.things.transport.*;
import com.instpower.things.config.Configs;
import com.instpower.things.util.CabinetQueryUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Handler0901Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/3/13
 * @Version: 1.0.0
 * @Description: 登录处理,建立连接session
 */

@Component(value = "CMD0901")
public class Handler0901Action extends Handler<Request> {
    @Override
    public short getId() {
        return Configs.LOGIN;
    }

    @Autowired
    private InstService instService;

    @Override
    public void execute(Connection connection, Request data) throws UnsupportedEncodingException {
        String sn = data.getHeader().getAddr();
        long begin = System.currentTimeMillis();
        logger.info("[{}]:Exec - CMD0901 - BEGIN",sn);
        Response response = new Response();
        Header header = new Header();
        header.setSyn(data.getHeader().getSyn());
        header.setRes(data.getHeader().getRes());
        header.setAddr(data.getHeader().getAddr());
        header.setPtrol(data.getHeader().getPtrol());
        header.setLength((short)3);
        header.setCommand(data.getHeader().getCommand());
        response.setHeader(header);
        MTData mData = new MTData();
        mData.setDatas(new byte[]{0x00});
        response.setData(mData);

        //设备版本，需要同步到数据库
        StringBuilder version = new StringBuilder();
        DataBuffer buffer = data.getData().encode();
        buffer.readByteArray(4);
        byte[] bytes = buffer.readByteArray(4);

        //release after read
        buffer.release();

        for(byte currByte : bytes){
            version.append(Byte.toUnsignedInt(currByte)).append(".");
        }
        version.deleteCharAt(version.length()-1);
        //登录包创建session
        String cabinetSn = header.getAddr();
        //检测session,当前连接的connection是否已经发生变化
        DeviceSession oldSession =  DeviceSessionManager.getInstance().get(cabinetSn);
        if(oldSession==null || (oldSession.getMConnection()!=null && !connection.getId().equals(oldSession.getMConnection().getId()))){
            DeviceSession deviceSession = new DeviceSession(connection, cabinetSn);
            logger.info("build session,机柜:{},new deviceSession:{}",cabinetSn,deviceSession.hashCode());
            DeviceSessionManager.getInstance().add(deviceSession);
        }
        logger.info("0901,建立链接后,map中数据是:{}", DeviceSessionManager.getInstance().sessions());

        this.sendResponse(connection, response);

        //更新机柜设备状态,带上机柜版本
        instService.updateCabinetOnline(header.getAddr(), version.toString());
        logger.debug("[{}]:Exec - CMD0901 updateCabinetOnline used {}",sn,System.currentTimeMillis()-begin);

        logger.info("[{}]:Exec - CMD0901 - END",sn);

        connection.getmContext().channel().eventLoop().schedule(()->{
            CabinetQueryUtil.cabinetQuery(cabinetSn);
        },10L, TimeUnit.SECONDS);
    }
}
